import { ADD_TODO, DEL_TODO, UPDATE_TODO, SELECT_ALL } from "../types";

// 定义一个函数，该函数用来获取选中的数量和是否被全选
function selectCountFn(list){
    // 将所有被选中的内容过滤出来
    const arr = list.filter(item => item.isSelect)

    return {
        selectCount: arr.length,
        isAll: arr.length === list.length
    }
}


const reducer = (state = {
    todoList: [
        {
            isSelect: false,
            title: '美美的睡上一觉',
            id: 'qwerpoioafaiofroiqji'
        },
        {
            isSelect: true,
            title: '吃上美美的美式',
            id: 'iosdfijhojajsdasd'
        }
    ], // 所有数据
    selectCount: 1, // 代表的是已经选中的数量
    isAll: false, // 代表的是，是否全选
}, {type, payload})=>{

    let obj = {}

    switch (type) {
        case ADD_TODO:
        
            // 先将添加的内放在数组中
            state.todoList.push(payload)

            obj = selectCountFn(state.todoList)

            return {...state, todoList: [...state.todoList], ...obj}
        case DEL_TODO:
            // 找到要删除元素的索引值
            const index = state.todoList.findIndex(item => {
                // 根据 id 找到要删除内容的索引值
                return item.id === payload.id
            })

            state.todoList.splice(index, 1)

            obj = selectCountFn(state.todoList)
            
            return {...state, todoList: [...state.todoList], ...obj}

        case UPDATE_TODO:
                // 找到要选择元素的索引值
                const index1 = state.todoList.findIndex(item => {
                    // 根据 id 找到要修改内容的索引值
                    return item.id === payload.id
                })
    
                // splice(开始位置，替换数量，替换内容)
                state.todoList.splice(index1, 1, payload)

                obj = selectCountFn(state.todoList)

                return {...state, todoList: [...state.todoList], ...obj}
        case SELECT_ALL :

            state.todoList.forEach(item => {
                item.isSelect = payload
            })

            obj = selectCountFn(state.todoList)

            return {...state, todoList: [...state.todoList], ...obj}
        default:
            return state
    }
}


export default reducer